package com.ruoyi.web.controller.system;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.InvoiceConfigDTO;
import com.ruoyi.common.core.domain.entity.InvoiceRequest;
import com.ruoyi.common.core.domain.entity.SystemConfig;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.FaPiao;
import com.ruoyi.system.domain.TcyPlatformOrder;
import com.ruoyi.system.service.IFaPiaoService;
import com.ruoyi.system.service.ISystemConfigService;
import com.ruoyi.system.service.ITcyPlatformOrderService;
import com.ruoyi.system.service.InvoiceService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system/invoice")
public class InvoiceController extends BaseController {

    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    private ISystemConfigService systemConfigService;

    @Autowired
    private ITcyPlatformOrderService tcyPlatformOrderService;

    @Autowired
    private IFaPiaoService faPiaoService;


        /**
         * 开票接口
         * @param request 开票请求DTO
         * @return 统一响应结果
         */
        @PostMapping("/issue")
        public AjaxResult issue(@RequestBody InvoiceRequest request) {
            // 构建业务参数
            Map<String, Object> info = new HashMap<>();
            info.put("bz", request.getRemark());
            info.put("order_sn", request.getOrderSn());
            info.put("TotalAmount", request.getAmount());

            // 调用业务逻辑
            Map<String, Object> result = invoiceService.fpkj(info);

            // 转换为统一响应格式
            if ("0".equals(result.get("code"))) {
                return AjaxResult.success(result.get("content"));
            } else {
                return AjaxResult.error(result.get("msg").toString());
            }
        }






    /**
     * 接收发票异步回调通知
     */
    @PostMapping("/index")
    public Map<String, Object> receiveInvoiceCallback(@RequestBody Map<String, Object> postInfo) {
        logger.info("收到发票异步回调请求，请求数据：{}", postInfo);

        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "获取信息失败");

        try {
            // 验证请求数据
            if (postInfo == null || postInfo.isEmpty()) {
                logger.warn("发票回调请求数据为空，返回失败响应");
                return result;
            }

            // 记录回调基本信息
            String callbackCode = postInfo.get("code") != null ? postInfo.get("code").toString() : "null";
            logger.info("回调状态码：{}", callbackCode);

            // 处理发票开具成功通知
            if ("0".equals(callbackCode)) {
                Map<String, Object> content = (Map<String, Object>) postInfo.get("content");
                if (content != null) {
                    // 记录关键信息
                    String orderSn = (String) content.get("fpqqlsh");
                    String fphm = (String) content.get("fphm");
                    logger.info("发票开具成功，订单流水号：{}，发票号码：{}", orderSn, fphm);

                    // 更新发票信息
                    updateInvoiceInfo(content);
                    logger.info("发票信息更新成功，订单流水号：{}", orderSn);

                    // 更新订单状态
                    updateOrderStatus(content);
                    logger.info("订单状态更新为已开票，订单流水号：{}", orderSn);

                    result.put("code", 1);
                    result.put("msg", "成功");
                    logger.info("发票回调处理完成，返回成功响应");
                    return result;
                } else {
                    logger.warn("发票回调内容为空，状态码为0但无有效数据");
                }
            } else {
                String errorMsg = postInfo.get("msg") != null ? postInfo.get("msg").toString() : "未知错误";
                logger.warn("发票回调处理失败，状态码：{}，错误信息：{}", callbackCode, errorMsg);
            }

        } catch (Exception e) {
            logger.error("处理发票回调通知发生异常", e);
            result.put("msg", "处理失败: " + e.getMessage());
        }

        logger.info("发票回调处理结束，返回默认失败响应");
        return result;
    }




    /**
     * 接收发票异步回调通知
     */
//    @PostMapping("/index")
//    public Map<String, Object> receiveInvoiceCallback(@RequestBody Map<String, Object> postInfo) {
//        Map<String, Object> result = new HashMap<>();
//        result.put("code", 0);
//        result.put("msg", "获取信息失败");
//
//        try {
//            // 验证请求数据
//            if (postInfo == null || postInfo.isEmpty()) {
//                return result;
//            }
//
//            // 处理发票开具成功通知
//            if ("0".equals(postInfo.get("code"))) {
//                Map<String, Object> content = (Map<String, Object>) postInfo.get("content");
//                if (content != null) {
//                    // 更新发票信息
//                    updateInvoiceInfo(content);
//
//                    // 更新订单状态
//                    updateOrderStatus(content);
//
//                    result.put("code", 1);
//                    result.put("msg", "成功");
//                    return result;
//                }
//            }
//
//        } catch (Exception e) {
//            logger.error("处理发票回调通知失败", e);
//            result.put("msg", "处理失败: " + e.getMessage());
//        }
//
//        return result;
//    }

    /**
     * 添加发票信息--把开票过的数据，返回来的数据保存到数据表中
     */
    private void updateInvoiceInfo(Map<String, Object> content) {
        // 获取订单流水号，作为查询条件,就是调用开发票接口的时候，传给接口的订单号
        String orderSn = (String) content.get("fpqqlsh");

        // 构建发票信息
        FaPiao invoice = new FaPiao();
        invoice.setFphm((String) content.get("fphm"));
        invoice.setPdfUrl((String) content.get("pdfUrl"));
        // 已开票状态
        invoice.setKpStatus(2);
        invoice.setCreateTime(new Date());
        invoice.setOrderSn(orderSn);

        // 根据订单流水号更新发票信息
        faPiaoService.insertFaPiao(invoice);
    }

    /**
     * 更新订单状态为已开票
     */
    private void updateOrderStatus(Map<String, Object> content) {
        String outTradeNo = (String) content.get("fpqqlsh");
        // 更新订单为已开票状态
        tcyPlatformOrderService.updateKaipiaoStatusByOrderSn(outTradeNo, 2);
    }



    /**
     * 开票接口
     * @return 统一响应结果
     */
    @GetMapping("/qyxxcx")
    public AjaxResult qyxxcx() {

        Map<String, Object> result = invoiceService.qyxxcx();

        // 转换为统一响应格式
        if ("0".equals(result.get("code"))) {
            return AjaxResult.success(result.get("content"));
        } else {
            return AjaxResult.error(result.get("msg").toString());
        }
    }
    /**
     * 表单详情
     * @return 统一响应结果
     */

    @ApiOperation(value = "详情")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public AjaxResult info(SystemConfig systemConfig) {
        HashMap<String, String> m= systemConfigService.info(systemConfig.getFormName());
        return AjaxResult.success(m);
    }


    @PostMapping("/updateForm")
    public AjaxResult updateForm(@RequestBody InvoiceConfigDTO dto) {
        try {
            systemConfigService.updateForm(dto);
            return AjaxResult.success("更新成功");
        } catch (Exception e) {
            return AjaxResult.error("更新失败");
        }
    }




    /**
     * 待开发票分页
     */
    @GetMapping("/daikai")
    public TableDataInfo daikai(String openid) {
        startPage();
        List<TcyPlatformOrder> tcyPlatformOrderList = tcyPlatformOrderService.findUninvoicedOrders(openid);
        return getDataTable(tcyPlatformOrderList);
    }



//    /**
//     * 待开发票列表
//     */
//    @GetMapping("/daikai")
//    public AjaxResult daikai(String openid) {
//
//        // 查询待开发票的订单
//        List<TcyPlatformOrder> orderList = tcyPlatformOrderService.findUninvoicedOrders(openid);
//
//        return AjaxResult.success(orderList);
//    }

//    /**
//     * 已开发票列表页面
//     */
//    @GetMapping("/yikai")
//    public Result yikai(Integer sid, HttpServletRequest request) {
//        // 验证登录
//        MemberUser userInfo = authService.validateLogin(sid, request);
//
//        // 查询已开发票记录
//        List<Invoice> invoiceList = invoiceService.findInvoicedRecords(
//                userInfo.getMemberId(), sid);
//
//        // 格式化日期和状态
//        invoiceList.forEach(invoice -> {
//            invoice.setCreateTimeFormat(DateTimeFormatter.ofPattern("yyyy-MM-dd")
//                    .format(invoice.getCreateTime()));
//            // 设置状态描述
//            switch(invoice.getKpStatus()) {
//                case 2: invoice.setKptitle("已开"); break;
//                case 1: invoice.setKptitle("开票中"); break;
//                default: invoice.setKptitle("未开票");
//            }
//        });
//
//        Map<String, Object> result = new HashMap<>();
//        result.put("lists", invoiceList);
//        result.put("tenant_id", sid);
//        return Result.success(result);
//    }

    /**
     * 开发票接口
     */
//    @PostMapping("/kaipiao")
//    public Result kaipiao(Integer sid, Integer order_id, HttpServletRequest request) {
//        // 验证登录
//        MemberUser userInfo = authService.validateLogin(sid, request);
//
//        if (order_id == null || order_id <= 0) {
//            return Result.error("开票失败");
//        }
//
//        // 查询订单信息
//        CarOrder orderInfo = carOrderService.getOrderDetail(
//                userInfo.getMemberId(), sid, order_id);
//
//        if (orderInfo == null) {
//            return Result.error("订单不存在");
//        }
//
//        // 检查是否已经开过发票
//        boolean alreadyInvoiced = invoiceService.checkInvoiceExists(
//                userInfo.getMemberId(), sid, order_id);
//
//        if (alreadyInvoiced) {
//            return Result.error("该订单已经开过发票");
//        }
//
//        // 准备开票信息
//        InvoiceRequest invoiceRequest = new InvoiceRequest();
//        invoiceRequest.setOrderSn(orderInfo.getOrderSn());
//        invoiceRequest.setTotalAmount(orderInfo.getTotalAmount());
//        invoiceRequest.setBz("车牌:" + orderInfo.getCarSn() +
//                " 停车时间:" + DateTimeFormatter.ofPattern("yyyy-MM-dd")
//                .format(orderInfo.getPayTime()));
//
//        // 调用外部开票接口
//        InvoiceResponse kpInfo = invoiceApiService.createInvoice(invoiceRequest);
//
//        if (kpInfo.getCode().equals("0")) {
//            // 开票成功，保存发票信息
//            Invoice invoice = new Invoice();
//            invoice.setOrderId(orderInfo.getOrderId());
//            invoice.setMemberId(orderInfo.getMemberId());
//            invoice.setTenantId(orderInfo.getTenantId());
//            invoice.setCreateTime(LocalDateTime.now());
//            invoice.setKpStatus(2);
//            invoice.setSzFpqqlsh(kpInfo.getContent().getSzFpqqlsh());
//            invoice.setPdfUrl(kpInfo.getContent().getUrlQRCode());
//
//            invoiceService.saveInvoice(invoice);
//
//            // 更新订单状态为已开票
//            carOrderService.updateOrderInvoiceStatus(order_id, 2);
//
//            return Result.success("开票成功", kpInfo.getContent().getUrlQRCode());
//        } else {
//            // 记录失败日志
//            String logMsg = "时间:" + LocalDateTime.now() +
//                    ",car_sn:" + orderInfo.getCarSn() +
//                    ",TotalAmount:" + orderInfo.getTotalAmount() +
//                    ",order_sn:" + orderInfo.getOrderSn() +
//                    ",msg:" + kpInfo.getMsg();
//
//            invoiceService.logInvoiceFailure(logMsg);
//            return Result.error("开票失败");
//        }
//    }

    /**
     * 查询发票状态
     */
//    @GetMapping("/chaxun")
//    public Result chaxun(Integer sid, Integer order_id, HttpServletRequest request) {
//        // 验证登录
//        MemberUser userInfo = authService.validateLogin(sid, request);
//
//        // 查询发票信息
//        Invoice fpInfo = invoiceService.getInvoiceByOrderId(
//                userInfo.getMemberId(), sid, order_id);
//
//        if (fpInfo != null && fpInfo.getKpStatus() == 2) {
//            return Result.success("成功", fpInfo.getPdfUrl());
//        } else {
//            return Result.error("开票中");
//        }
//    }












}
